Demo Trait trong laravel 9

Nếu trong model chúng ta có scrope thì trong Controller chúng ta có trait .Trait giúp chúng ta rút gọn đáng kể code .
Khi học code bắt đầu thì các bạn thường học CRUD .Vấn đề là khi có 1 CRUD thì không sao nhưng mà khi mà có nhiều thì làm sao có thể rút gọn đây .Trait sinh ra để xử lý các vấn đề này
Bước 1 tạo app demo với lệnh :
composer create-project laravel/laravel trait
Tiếp theo chúng ta sử dụng lệnh tạo resource demo:
php artisan make:model Post --all
Tạo router demo ở file routes/web.php :
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::resource('/posts',\App\Http\Controllers\PostController::class);
Route::get('/', function () {
return view('welcome');
});
Tạo 1 trait với lệnh sau :
php artisan make:trait HasActionController
Code như sau :
namespace App\Traits;
trait HasActionController
{
public function index()
{
$name = $this->model->getTable();
$views = $name .'.index';
return view($views);
}
}
Do chỉ là demo nên mình chỉ code phần index
Chỉnh sửa file PostController :
namespace App\Http\Controllers;
use App\Models\Post;
use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Traits\HasActionController;
class PostController extends Controller
{
use HasActionController;
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
protected $model;
public function __construct()
{
$this->model = new Post();
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \App\Http\Requests\StorePostRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StorePostRequest $request)
{
//
}
/**
* Display the specified resource.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function show(Post $post)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \App\Http\Requests\UpdatePostRequest $request
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function update(UpdatePostRequest $request, Post $post)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
//
}
}
Ở đây chúng ta chỉ cần dùng lệnh use HasActionController là xong .Đỡ bao nhiêu code
Demo mình để ở dưới các bạn download về và xem